using System;

namespace org.lionsoul.ip2region.test
{



	/// <summary>
	/// project test script
	/// 
	/// @author chenxin<chenxin619315@gmail.com>
	/// </summary>
	public class TestSearcher
	{
		public static void Main(string[] argv)
		{
			if (argv.Length == 0)
			{
				Console.WriteLine("| Usage: java -jar ip2region-{version}.jar [ip2region db file]");
				return;
			}

			int algorithm = org.lionsoul.ip2region.DbSearcher.BTREE_ALGORITHM;
			File file = new File(argv[0]);
			if (file.exists() == false)
			{
				Console.WriteLine("Error: Invalid ip2region.db file");
				return;
			}

			if (argv.Length > 1)
			{
				if (argv[1].ToUpper() == "binary".ToUpper())
				{
					algorithm = org.lionsoul.ip2region.DbSearcher.BIN_ALGORITHM;
				}
			}

			try
			{
				Console.WriteLine("initializing " + ((algorithm == 2)?"Binary":"B-tree") + " ... ");
				org.lionsoul.ip2region.DbConfig config = new org.lionsoul.ip2region.DbConfig();
				org.lionsoul.ip2region.DbSearcher seacher = new org.lionsoul.ip2region.DbSearcher(config, argv[0]);
				java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

				Console.WriteLine("+----------------------------------+");
				Console.WriteLine("| ip2region test shell             |");
				Console.WriteLine("| Author: chenxin619315@gmail.com  |");
				Console.WriteLine("| Type 'quit' to exit program      |");
				Console.WriteLine("+----------------------------------+");

				double sTime = 0, cTime = 0;
				string line = null;
				org.lionsoul.ip2region.DataBlock dataBlock = null;
				while (true)
				{
					Console.Write("ip2region>> ");
					line = reader.readLine().Trim();
					if (line.Length < 2)
					{
						continue;
					}
					if (line.ToUpper() == "quit".ToUpper())
					{
						break;
					}
					if (org.lionsoul.ip2region.Util.isIpAddress(line) == false)
					{
						Console.WriteLine("Error: Invalid ip address");
						continue;
					}

					sTime = System.nanoTime();
					dataBlock = algorithm == 2 ? seacher.binarySearch(line) : seacher.btreeSearch(line);
					cTime = (System.nanoTime() - sTime) / 1000000;
					Console.Write("{0} in {1:F5} millseconds\n", dataBlock, cTime);
				}

				reader.close();
				seacher.close();
				Console.WriteLine("+--Bye");
			}
			catch (java.io.IOException e)
			{
				// TODO Auto-generated catch block
				Console.WriteLine(e.ToString());
				Console.Write(e.StackTrace);
			}
			catch (org.lionsoul.ip2region.DbMakerConfigException e)
			{
				// TODO Auto-generated catch block
				Console.WriteLine(e.ToString());
				Console.Write(e.StackTrace);
			}
		}
	}

}